import cocos, pyglet, random
from cocos.actions import *
from cocos.scenes import *
from cocos.director import director

import models, gui, cutscenes, menu, sound
from config import current as conf

class HordesLayer(cocos.layer.Layer):
    """Displays the zombie hordes"""
    def __init__(self, state, gamegrid):
        super(HordesLayer, self).__init__()
        self.state = state
        self.gamegrid = gamegrid
        for horde in state.hordes:
            self.add_horde(horde)
        self.state.handle("new_horde", self.add_horde)

    def add_horde(self, horde):
        self.add(HordeLayer(horde, self.gamegrid))

class HordeLayer(cocos.layer.Layer):
    def __init__(self, horde, gamegrid):
        super(HordeLayer, self).__init__()
        self.horde = horde
        self.gamegrid = gamegrid
        self.horde.handle("move", self.move)
        self.horde.handle("death", self.death)
        self.horde.handle("attack", self.attack)
        
        self.position = gamegrid.cell_to_pixel(horde.location)
        self.sprite = cocos.sprite.Sprite('zombie-sprite.png')
        self.sprite.anchor_y = 'bottom'
        self.add(self.sprite)

    def move(self, old, new):
        time = .5 + random.random()
        self.do(MoveTo(self.gamegrid.cell_to_pixel(new), time))

    def death(self):
        self.sprite.do(FadeOut(0.5) + CallFunc(lambda: self.parent.remove(self)))

    def attack(self, city):
        old = self.position
        new = self.gamegrid.cell_to_pixel(city.location)
        self.do(AccelDeccel(MoveTo(new, 0.2) + MoveTo(old, 0.2)))
        sound.snarl()
